<template>
<div class="goodsAttrs">
  <el-tabs tab-position="left">
    <el-tab-pane label="规格">
      <search-block v-if="!disabled && goodsTag !== undefined">
        <template slot="button">
          <el-button type="primary" @click="addSpecName">添加</el-button>
        </template>
        <el-form inline :model="this" label-width="100px" @submit.native.prevent>
          <el-form-item label="规格名称:">
            <el-input v-model="specInput" :maxlength="10" show-word-limit></el-input>
          </el-form-item>
        </el-form>
      </search-block>
      <el-collapse accordion v-model="activeName" v-if="Object.keys(specObj).length">
        <el-collapse-item
          v-for="(name, index) in Object.keys(specObj)"
          :key="index"
          :name="name">
          <div class="coll-title" slot="title">
            <span>{{name}}</span>
            <el-button type="primary" size="mini" @click.stop="showAddSpec(name)" v-if="!disabled">添加规格值</el-button>
          </div>
          <y-table
            border
            :columns="specColumns"
            :get-data-way="{
              data: specObj[name]
            }">
            <el-table-column slot="icon" label="图标" align="center" header-align="center" width="130">
              <template v-slot="scope">
                <img v-if="scope.row.icon" style="height: 100px" :src="generateMediaUrl({fileOpenUrl: scope.row.icon})"/>
              </template>
            </el-table-column>
            <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="80"  v-if="!disabled">
              <template v-slot="scope">
                <div class="table-buttons">
                  <el-popconfirm
                    title="是否确认删除该规格值？"
                    @confirm="removeSpecItem(scope.row)">
                    <el-button slot="reference" type="danger" size="mini">删除</el-button>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </y-table>
        </el-collapse-item>
      </el-collapse>
      <y-form
        ref="yForm"
        v-model="forms.formModel"
        :visible.sync="forms.showForm"
        :title="`添加[${forms.currentName}]规格值`"
        destroy-on-close
        append-to-body
        width="50%"
        :form-attrs="forms.formAttrs"
        :columns="forms.formColumns"
        @closed="resetSpecModel"
        @ensure="ensureModel">
        <template slot="icon">
          <y-upload-img
            business-sys-module-code="GOODS_ATTRIBUTE"
            :limit="1"
            :cropper-options="{
              fixedNumber: [1, 1],
              centerBox: false
            }"
            :url="forms.formModel.icon ? [{
              url: forms.formModel.icon,
              id: forms.formModel.attachmentId
            }] : []"
            value-type="ObjectArray"
            @update="updateModel"
            re-upload>
          </y-upload-img>
        </template>
      </y-form>
    </el-tab-pane>
    <el-tab-pane label="参数">
      <div class="attrs-form edit-table-form">
        <div class="form-row saved-row" v-for="(item, index) in attrsList" :key="index">
          <el-input v-model="item.name" readonly style="width: 100px" placeholder="参数名"></el-input>:
          <el-input v-model="item.value" readonly style="flex-grow: 2;flex-shrink: 1" placeholder="参数值"></el-input>
          <template v-if="!disabled">
            <el-divider direction="vertical"></el-divider>
            <el-popconfirm
                title="是否确认删除该参数？"
                @confirm="removeAttrsItem(item)">
              <el-button slot="reference" type="danger" icon="el-icon-delete" circle></el-button>
            </el-popconfirm>
          </template>
        </div>
        <div class="form-row" v-if="!disabled">
          <el-input v-model="addAttrs.name" style="width: 100px" placeholder="参数名"></el-input>:
          <el-input v-model="addAttrs.value" style="flex-grow: 2;flex-shrink: 1" placeholder="参数值"></el-input>
          <el-divider direction="vertical"></el-divider>
          <el-button type="primary" icon="fa fa-save" circle @click="saveAttrsItem()"></el-button>
        </div>
      </div>
    </el-tab-pane>
  </el-tabs>
</div>
</template>

<script>
export default {
  name: "goodsAttrs",
  inject: ['generateMediaUrl'],
  props:{
    productId: String,
    disabled: Boolean
  },
  data(){
    return{
      goodsTag: undefined,
      attrsList: [],
      addAttrs: {
        name: '',
        value: ''
      },
      specObj: {},
      specInput: '',
      activeName: '',
      specColumns: [{
        label: '属性值',
        prop: 'value'
      },{
        label: '图标',
        prop: 'icon',
        template: true
      }],
      forms:{
        formModel:{
          value: '',
          icon: ''
        },
        currentName: '',
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            value: [{required: true, message: "请输入属性值", trigger: "blur"}]
          }
        },
        formColumns: [{
          label: "属性值",
          prop: "value",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 20,
              showWordLimit: true
            }
          }
        },{
          label: "图标",
          prop: "icon",
          template: true
        }]
      }
    }
  },
  mounted(){
    this.initGoodsTag();
    this.refreshAttrs();
    this.refreshSpec();
  },
  methods:{
    initGoodsTag(){
      if(!this.disabled){
        this.$yAxios({
          url: this.$api.goods.getInfo,
          data:{
            id: this.productId
          },
          loading: true
        }, info => {
          this.goodsTag = info.tag;
        })
      }
    },
    saveAttrsItem(){
      if(!this.addAttrs.name){
        this.$alert('请输入参数名', {
          confirmButtonText: '确定'
        });
        return;
      }
      if(!this.addAttrs.value){
        this.$alert('请输入参数值', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.$yAxios({
        url: this.$api.goods.addAttrs,
        data: {
          ...this.addAttrs,
          productId: this.productId,
          category: 2
        },
        loading: true
      }, info => {
        this.addAttrs.name = '';
        this.addAttrs.value = '';
        this.refreshAttrs();
      });
    },
    removeAttrsItem(item){
      this.$yAxios({
        url: this.$api.goods.removeAttrs,
        data:{
          id: item.id
        },
        loading: true
      }, info => {
        this.refreshAttrs();
      });
    },
    refreshSpec(){
      this.$yAxios({
        url: this.$api.goods.selectSpec,
        data: {
          productId: this.productId
        },
        loading: true
      }, info => {
        if(info){
          this.$set(this, 'specObj', info);
        }
      });
    },
    refreshAttrs(){
      this.$yAxios({
        url: this.$api.goods.selectAttrs,
        data: {
          productId: this.productId,
          category: 2
        },
        loading: true
      }, info => {
        if(info){
          this.attrsList = info;
        }
      });
    },
    addSpecName(){
      if(!this.specInput) return;
      if(this.specObj){
        if(this.goodsTag === 1 && Object.keys(this.specObj).length){
          this.$message({
            type: 'warning',
            message: '商品只允许存在一种规格'
          });
          return;
        }
        if(Object.keys(this.specObj).includes(this.specInput)){
          //
        }else{
          this.$set(this.specObj, this.specInput, []);
        }
        this.activeName = this.specInput;
      }
    },
    removeSpecItem(item){
      this.$yAxios({
        url: this.$api.goods.removeAttrs,
        data:{
          id: item.id
        },
        loading: true
      }, info => {
        this.refreshSpec();
        this.$emit("reset-sku");
      });
    },
    showAddSpec(title){
      if(this.goodsTag === 1 && this.specObj[title].length){
        this.$message({
          type: 'warning',
          message: '商品只允许存在一种规格项'
        });
        return;
      }
      this.forms.currentName = title;
      this.forms.showForm = true;
    },
    resetSpecModel(){
      this.forms.formModel.value = '';
      this.forms.formModel.icon = '';
    },
    updateModel({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.attachmentId = '';
          this.forms.formModel.icon = '';
          break;
        }
        case 'edit': case 'add':{
          this.forms.formModel.attachmentId = file.id;
          this.forms.formModel.icon = file.name;
          this.$refs['yForm'].$refs['form'].validateField('icon');
          break;
        }
      }
    },
    ensureModel(form){
      this.$yAxios({
        url: this.$api.goods.addAttrs,
        data: {
          ...form,
          name: this.forms.currentName,
          productId: this.productId,
          category: 1
        },
        loading: true
      }, info => {
        this.refreshSpec();
        this.activeName = this.forms.currentName;
        this.$emit("reset-sku");
      });
    },
    save(){
      return new Promise(resolve => {
        if(!Object.keys(this.specObj).length){
          this.$message({
            type: 'warning',
            message: '请至少录入一条规格'
          });
          resolve(false);
        }
        resolve(true);
      });
    }
  }
}
</script>

<style scoped lang="less">
.goodsAttrs{
  height: 100%;
  >.el-tabs{
    height: 100%;
    overflow: hidden;
    /deep/ .el-tabs__content{
      height: 100%;
      overflow-x: hidden;
      overflow-y: auto;
    }
  }
  /deep/.coll-title{
    padding: 0 20px;
    >span{
      display: inline-block;
      min-width: 150px;
    }
    >.el-button{
      margin-left: 20px;
    }
  }
  .el-collapse{
    border-top: 0;
    /deep/.el-collapse-item__header.is-active{
      border-bottom: @common-border;
      >.coll-title>span{
        color: #409EFF
      }
    }
  }
}
</style>